package com.reducejoin;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.springframework.beans.BeanUtils;

import java.io.IOException;
import java.util.ArrayList;

public class TableReducer extends Reducer<Text, TableBean, TableBean, NullWritable> {

    @Override
    protected void reduce(Text key, Iterable<TableBean> values, Context context) throws IOException, InterruptedException {
        ArrayList<TableBean> orderBean = new ArrayList<>();
        TableBean pdBean = new TableBean();

        for (TableBean value : values) {

            if ("order".equals(value.getFlag())) {
                TableBean tmpOrderBean = new TableBean();
                BeanUtils.copyProperties(value, tmpOrderBean);

                orderBean.add(tmpOrderBean);
            } else {
                BeanUtils.copyProperties(value, pdBean);
            }
        }

        for (TableBean tableBean : orderBean) {
            tableBean.setPname(pdBean.getPname());
            context.write(tableBean, NullWritable.get());
        }
    }
}
